iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 21
0

Custom Header

可以自行指定,也是傳入dictionary即可

POST Content Type

  • 'Content-Type': 'multipart/form-data'
    • 使用fields
  • 'Content-Type': 'application/json'
    • 使用body參數
import urllib3
import json

http = urllib3.PoolManager()

r = http.request('POST', 'http://httpbin.org/post', fields={'key1': 'value1', 'key2': 'value2'})
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('headers'))
print(r_json.get('form'))


data = {'some': 'data'}
encoded_data = json.dumps(data).encode('utf-8')
r = http.request('POST', 'http://httpbin.org/post', body=encoded_data, headers={'Content-Type': 'application/json'})
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('headers'))
print(r_json.get('json'))


with open('example.txt') as fp:
    file_data = fp.read()
    r = http.request('POST', 'http://httpbin.org/post',
                     fields={'file-to-upload': ('example.txt', file_data)}
                     )
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('headers'))
print(r_json.get('files'))


with open('wolf.jpg', 'rb') as fp:
    file_data = fp.read()
    r = http.request('POST', 'http://httpbin.org/post',
                     fields={'file-field': ('wolf.jpg', file_data)}
                     )
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('headers'))
print(r_json.get('files'))


with open('wolf.jpg', 'rb') as fp:
    binary_data = fp.read()
    r = http.request('POST', 'http://httpbin.org/post',
                     body=binary_data, headers={'Content-Type': 'image/jpeg'}
                     )
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('headers'))
print(r_json.get('data'))

參考


上一篇
Day20-urllib3-User Guide-1
下一篇
Day22-urllib3-User Guide-3
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言